package com.tianzhu.web.admin;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tianzhu.domain.Product;
import com.tianzhu.service.ProductService;

@Controller
@RequestMapping("/admin")
public class AdminProduct {

  
    @Autowired
    private ProductService productService;

    @RequestMapping("/product/addProduct")
    public String addProduct(Model model){
        Product product = new Product();
        product.setProductcategory("instrument");
        product.setProductcondition("new");
        product.setProductstatus("active");

        model.addAttribute("product", product);

        return "pages/addProduct";
    }

    @RequestMapping(value="/product/addProduct", method = RequestMethod.POST)
    public String addProductPost(@Valid @ModelAttribute("product") Product product, BindingResult result, HttpServletRequest request){

        if(result.hasErrors()){
            return "pages/addProduct";
        }

        productService.addProduct(product);

        return "redirect:/admin/productInventory";
    }

    @RequestMapping("/product/editProduct/{id}")
    public String editProduct(@PathVariable("id") Long id,  Model model){
        Product product = productService.getProductById(id);

        model.addAttribute("product", product);

        return "pages/editProduct";
    }


    @RequestMapping(value="/product/editProduct", method = RequestMethod.POST)
    public String editProductPost(@Valid @ModelAttribute("product") Product product, BindingResult result){

        if(result.hasErrors()){
            return "pages/editProduct";
        }

        productService.editProduct(product);

        return "redirect:/admin/productInventory";
    }


    @RequestMapping("/product/deleteProduct/{id}")
    public String deleteProduct(@PathVariable Long id, Model model){
       
        Product product = productService.getProductById(id);
        productService.deleteProduct(product);

        return "redirect:/admin/productInventory";
    }

} // The End of Class;
